<?php

namespace Vietland\AdsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Vietland\AdsBundle\Form\Type\PostFormType;
use Vietland\AdsBundle\Document\Post;
use Vietland\UserBundle\Document\User;
use Vietland\AdsBundle\Document\Image;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class PostController extends Controller {

    /**
     * @Route("/", name="_vietland_index", defaults={"_format"="html"})
     */
    public function indexAction() {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof User) {
            $user = false;
        }
        $dm = $this->get('doctrine.odm.mongodb.document_manager');
        //prepare category for homepage
        $categories = $dm->getRepository("VietlandAdsBundle:Category")->findAll();
        //get top post
        $posts = $dm->createQueryBuilder('VietlandAdsBundle:Post')
                ->limit(14)->sort('id', 'desc')
                ->getQuery()
                ->execute();
        //separate posts into columns
        $index = 0;
        //column 1
        $column3 = array();
        //column 2
        $column2 = array();
        //column 3
        $column1 = array();
        $index = 0;
        foreach ($posts as $post) {
            if ($index < 4) {
                $column1[] = $post;
            } elseif ($index < 9) {
                $column2[] = $post;
            } else{
                $column3[] = $post;
            }
            $index++;
        }

        $content = $this->renderView('VietlandAdsBundle:Post:index.html.twig', array('user' => $user,
            'categories' => $categories,
            'column1' => $column1,
            'column2' => $column2,
            'column3' => $column3,
            'foo' => time()
                )
        );
        $response = new Response($content);
        $response->headers->set('Cache-Control', 'no-cache');
        return $response;
    }

    /**
     * @Route("/post/index.{_format}", name="_vietland_new_post")
     */
    public function newPostAction($_format) {
        $postType = new PostFormType();
        $postType->setTranslator($this->get('translator'));
        $post = new Post();
        $form = $this->createForm($postType, $post);
        $response = new Response($this->renderView('VietlandAdsBundle:Post:newPost.html.twig', array('form' => $form->createView(), 'foo' => time())));
        $response->headers->set('Cache-Control', 'no-cache');
        return $response;
    }

    /**
     *
     * @Route("/create/{foo}.{_format}", name="_vietland_create_post", defaults={"foo"="0", "_format"="json"})
     */
    public function createPostAction($_format) {
        $request = $this->get('request');
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !($user instanceof User)) {
            $response = new Response(json_encode(array('status' => false, 'message' => 'Bạn cần phải đăng nhập trước khi đăng bài.')));
            return $response;
        }
        if ('POST' === $request->getMethod()) {
            $post = new Post();
            $dm = $this->get('doctrine.odm.mongodb.document_manager'); //MongoDB Document Manager
            $post->setDm($dm);
            $postType = new PostFormType();
            $postType->setTranslator($this->get('translator'));
            //create form for validate
            $form = $this->createForm($postType, $post);
            //new form for next post
            $newform = $this->createForm($postType, new Post());
            $form->bindRequest($request);
            if ($form->isValid() && $_format == "json" && is_object($user) && $user instanceof User) {
                //get current user and check it before manipulate data
                $user = $this->container->get('security.context')->getToken()->getUser();
                if (is_object($user) || $user instanceof User) {
                    $post->setUser($user);
                }
                //
                if ($_FILES) {
                    $files = array();
                    $imageMirror = new Image();
                    $kernel = $this->get('kernel');
                    $rootDir = $kernel->getRootDir();
                    $physicalWebDir = str_replace(
                            DIRECTORY_SEPARATOR . 'app', DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR, $rootDir);
                    for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
                        $path = $physicalWebDir . basename($_FILES['images']['name'][$i]);
                        move_uploaded_file($_FILES['images']['tmp_name'][$i], $path);
                        $newImage = clone $imageMirror;
                        $newImage->setFile($path);
                        $newImage->setName($_FILES['images']['name'][$i]);
                        $post->setImages($newImage);
                        $dm->persist($newImage);
                        $files[] = $path;
                    }
                }
                $dm->persist($post);
                $dm->flush();
                if (!empty($files))
                    foreach ($files as $file) {
                        unlink($file);
                    }
                $response = new Response(json_encode(array('status' => true, 'id' => $post->getSlug(), 'foo' => time(), 'form' => $this->renderView('VietlandAdsBundle:Post:newPost.html.twig', array('form' => $newform->createView(), 'foo' => time())))));
                $response->headers->set('Cache-Control', 'no-cache');
                return $response;
            } else {
                var_dump($form->getErrors());
                exit;
            }
        }
    }

    /**
     * @Route("progress/{foo}.{_format}", name="_vietland_get_progress", defaults={"_format"="json"})
     */
    public function getProgressAction($foo, $_format) {
        $status = uploadprogress_get_info($foo);

        if ($status) {
            return new Response(json_encode(array('percent' => round($status['bytes_uploaded'] / $status['bytes_total'] * 100))));
        } else {
            return new Response(json_encode(array('percent' => 100)));
        }
    }

    /**
     * @Route("uploadedimage/{id}/{img_index}", name="_vietland_get_postimage")
     */
    public function getPostImageAction($id, $img_index) {
        $dm = $this->get('doctrine.odm.mongodb.document_manager');
        $postid = (int) ($id);
        $img_index = (int) $img_index;
        $post = $dm->getRepository('VietlandAdsBundle:Post')->findOneById($postid);
        $image = $post->getImages($img_index);
        header('Content-Type: image/png;');
        echo $image->getFile()->getBytes();
        exit;
    }

    /**
     * @Route("user/{id}/{img_index}", name="_vietland_get_userimage")
     */
    public function getUserImageAction($id, $img_index) {
        $dm = $this->get('doctrine.odm.mongodb.document_manager');
        $userid = (int) ($id);
        $img_index = (int) $img_index;
        $post = $dm->getRepository('VietlandUserBundle:User')->findOneById($userid);
        $image = $post->getAvatars($img_index);
        header('Content-Type: image/png;');
        echo $image->getFile()->getBytes();
        exit;
    }

    //You do not need to alter these functions
    private function resizeImage($image, $width, $height, $scale) {
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
        $extension = 'null';
        if ($image_type = exif_imagetype($image)) {
            $extension = image_type_to_extension($image_type, false);
        }
        switch ($extension) {
            case 'png':
                $source = imagecreatefrompng($image);
                break;
            case 'jpeg':
                $source = imagecreatefromjpeg($image);
                break;
            case 'gif':
                $source = imagecreatefromgif($image);
                break;
        }
        imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
        imagejpeg($newImage, $image, 90);
        chmod($image, 0777);
        return $image;
    }

    //You do not need to alter these functions
    function getHeight($image) {
        $sizes = getimagesize($image);
        $height = $sizes[1];
        return $height;
    }

    //You do not need to alter these functions
    function getWidth($image) {
        $sizes = getimagesize($image);
        $width = $sizes[0];
        return $width;
    }

}